/*
  1. Promise就是一个类，在执行这个类的时候，需要传递一个执行器进去，执行器会立即执行
  2. Promise中有三种状态，分别为成功 fulfilled,失败 rejected, 等待 pending
    pending -> fulfilled
    pending -> rejected 
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就是判断状态，状态成功，调用成功的回调，如果失败就调用失败的回调，then方法是被定义在原型中的
  5. then成功回调和失败都有一个参数
*/
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (err) {
      this.reject(err);
    }
  }

  status = PENDING;
  value = undefined; // 成功之后的值
  reason = undefined; // 失败的原因
  successCallback = [];
  failCallback = []

  resolve = value => {
    // 如果状态不是等待，阻止程序向下执行
    if (this.status !== PENDING) return;
    // 将状态更改为成功
    this.status = FULFILLED;
    // 保存成功之后的值
    this.value = value;
    // 判断成功回调是否存在，存在就调用
    while (this.successCallback.length) {
      this.successCallback.shift()();
    }
  }

  reject = reason => {
    // 如果状态不是等待，阻止程序向下执行
    if (this.status !== PENDING) return;
    // 将状态更改为失败
    this.status = REJECTED;
    // 保存失败的原因
    this.reason = reason;
    // 判断失败回调是否存在，存在就调用
    while (this.failCallback.length) {
      this.failCallback.shift()();
    }
  }

  then(successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => {throw reason;}
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值，直接调用resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 再根据promise对象返回的结果，决定调用resolve还是调用reject
            resolvePromise(promise2, x, resolve, reject);
          } catch (err) {
            reject(err);
          }
        }, 0);
      } else if (this.status === REJECTED) {    
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);;
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值，直接调用resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 再根据promise对象返回的结果，决定调用resolve还是调用reject
            resolvePromise(promise2, x, resolve, reject);
          } catch (err) {
            reject(err);
          }
        }, 0);
      } else {
        // 等待
        // 将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值，直接调用resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 再根据promise对象返回的结果，决定调用resolve还是调用reject
              resolvePromise(promise2, x, resolve, reject);
            } catch (err) {
              reject(err);
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);;
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值，直接调用resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 再根据promise对象返回的结果，决定调用resolve还是调用reject
              resolvePromise(promise2, x, resolve, reject);
            } catch (err) {
              reject(err);
            }
          }, 0);
        });
      }
    });

    return promise2;
  }

  finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason });
    })
  }

  catch(failCallback) {
    return this.then(undefined, failCallback);
  }

  static all (array) {
    let result = []
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        index++;
        result[key] = value;
        if(index === array.length) {
          resolve(result);
        }
      }
      for(let i = 0; i < array.length; i++) {
        let current = array[i];
        if(current instanceof MyPromise) {
          // promise对象
          current.then(value => {
            addData(i, value)
          }, reason => {
            reject(reason);
          })
        } else {
          // 普通值
          addData(i, array[i]);
        }
      }
    })
  }

  static race(array) {
    let isReturn = false;
    return new MyPromise((resolve, reject) => {
      function returnFunc(value) {
        if(!isReturn) {
          isReturn = true;
          resolve(`first ${value}`);
        }
      }

      for(let i = 0; i < array.length; i++) {
        let current = array[i];
        if(current instanceof MyPromise) {
          current.then(returnFunc, returnFunc);
        } else {
          returnFunc(current);
        }
      }
    })
  }

  static resolve(value) {
    if(value instanceof MyPromise) {
      return value;
    }
    return new MyPromise(resolve => resolve(value))
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}

module.exports = MyPromise;